package com.jf.blogbackened.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: GZL
 * Time: 2020/7/23 14:27
 */
public class OSSUtil {


    private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAI4G8zHYsDizPXSvgJPccV";
    private static String accessKeySecret = "lvzNO0DZBBWGSHj0L1HJ4mmLpluaXT";
    private static String bucketName = "david1234";

    public static String path="https://david1234.oss-cn-hangzhou.aliyuncs.com/";

    public static MultipartFile getMultipartFile(HttpServletRequest request){
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        MultipartHttpServletRequest multipartHttpServletRequest = resolver.resolveMultipart(request);
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        MultipartFile file =null;
        for (Map.Entry<String,MultipartFile> entry : fileMap.entrySet()){
           file = entry.getValue();
        }
        return file;

    }
    public static String putObject(MultipartFile file){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
        String newName = getNewName(file.getOriginalFilename());
        try {
            ossClient.putObject(bucketName, newName, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭OSSClient。
        ossClient.shutdown();

        return path+newName;
    }

    /**
     * 获取文件的新名称
     * @param oldName
     *      文件旧名称
     * @return
     *      文件新名称: uuid+时间戳.后缀名
     */
    public static String getNewName(String oldName){
        // 获取图片后缀名
        String suffixName = getFileSuffix(oldName);
        String newName= UUID.randomUUID().toString()+System.currentTimeMillis()+suffixName;
        return newName;
    }

    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static void del(String newName){
        String objectName = newName;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, objectName);
        ossClient.shutdown();
    }
}
